package mypackage;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.RecordControl;

import net.rim.device.api.media.control.AudioPathControl;


public class RecordThread extends Thread
{
	private Player player;
	
	private RecordControl rcontrol;
	
	private int buffSize = 100 * 1024;
	
//	private ByteArrayOutputStream _output;
	
	private byte[] data = new byte[buffSize];
	
	private int sum = 0;
	
	private OutputStream output = new OutputStream()
    {
		
        public void write(byte[] buffer, int offset, int count)
        {
        	Log.d("write","time: " + System.currentTimeMillis());
        	
        	if((sum + count) < buffSize)
        	{
        		System.arraycopy(buffer, offset, data, sum, count);
        	}
        	
        	sum = sum + count;
        }
        
        public void write(byte[] buffer) throws IOException
        {
            write(buffer, 0, buffer.length);
        }
        
        public void write(int b) throws IOException
        {
            Log.d("write","not implement");
        }
    };
	
	
	public RecordThread()
	{
		
	}

	public void run() 
	{
		try{
            player = Manager.createPlayer("capture://audio?encoding=pcm");
            
            player.realize();
            
            // Get the RecordControl, configure the record stream,
            rcontrol = (RecordControl) player.getControl("RecordControl");
            
            // Create a ByteArray OutputStream to record the audio stream.
            
            //_output = new ByteArrayOutputStream();
            rcontrol.setRecordStream(output);
            rcontrol.startRecord();
            AudioPathControl  lPathCtr = (AudioPathControl) player.getControl("net.rim.device.api.media.control.AudioPathControl");
            lPathCtr.setAudioPath(AudioPathControl.AUDIO_PATH_HANDSET);

            player.start();
        }
        catch (final Exception e)
        {
        	Log.d("write","RUN Exception");
        	e.printStackTrace();
        }
	}
	
	
	public byte[] stop() 
	{
		try 
		{
			rcontrol.commit();
			//_data = _output.toByteArray();
			output.close();
			player.close();
			return data;
		} 
		catch (Exception e) 
		{
			Log.d("write","STOP Exception:" + e.toString());
			e.printStackTrace();
			return new byte[0];
		}
	}

}
